<?php
/**
 * Created by PhpStorm.
 * User: Admin
 * Date: 2018-06-28
 * Time: 19:46
 */

namespace app\api\model;


use app\api\service\Token as TokenService;
use app\lib\enum\OrderStatusEnum;
use app\lib\exception\OrderException;

class Comments extends BaseModel
{
    protected $table = 'we_comments';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    protected $hidden = ['user_id', 'delete_time', 'update_time'];

    // 用户评论
    public static function saveComment($oid, $commentsArray){
        $uid = TokenService::getCurrentUid();
        if(!empty($commentsArray)){
            foreach ($commentsArray as $comments){
                $comment = self::where('uid', '=', $uid)->where('pid', '=', $comments['pid'])->where('oid', '=', $oid)->find();
                if($comment != null){
                    throw new OrderException([
                        'code' => 201,
                        'msg' => '用户已评论，无需再次提交评论',
                        'errorCode' => 80008,
                    ]);
                }else{
                    $comment = new Comments();
                    $comment->uid = $uid;
                    $comment->oid = $oid;
                    $comment->pid = $comments['pid'];
                    $comment->content = $comments['comment'];
                    $result = $comment->save();
                }
            }
            return $result;
        }

    }
    // 评论后修改订单状态
    public function updateOrderStatus($oid){
        $orderss = Order::get($oid);
        if(!$orderss){
            throw new OrderException();
        }
        if($orderss->status != OrderStatusEnum::HAVE_THE_GOODS){
            throw new OrderException([
                'msg' => '未确认收货或已评价',
                'errorCode' => 80006,
                'code' => 403
            ]);
        }
        $orderss->status = OrderStatusEnum::HAVE_COMMRNTS;
        $result = $orderss->save();
        return $result;
    }

}